import React, { useState, useEffect, useRef } from 'react';
import styles from './index.module.less';
import FormGroup from '@/components/form-group';
import { FormListItem } from '@/components/form-group/interface';
// import classnames from 'classnames';
import ButtonFooterDetail from '@/components/button-footer-detail';
import { GetOutsideUserDetail, DeleteOutsideUser } from '@/services/member';
import { Toast } from 'antd-mobile-v2';
import { SecondConfirm } from '@/components/second-confirm';
import {
  SEX_MAP, ENJAMBMENT_TYPE_MAP, RESIDENT_TYPE_MAP, PEOPLE_STATUS_MAP, ISHAVE_MAP, PAYLOCATION_TYPE_MAP
} from '@/pages/member/constants';
import Avatar from '@/components/avatar';
import { GetProvince, GetCities, GetAreas, GetOccupationCode, GetCardTypeCode, GetCountryCode, GetBankArea, GetBanks } from '@/services/commons';
import { FormatDictData } from '@/utils/formatter';
import moment from 'moment';
const MemberDetail: React.FC<any> = (props) => {
  const formRef: React.MutableRefObject<any> = useRef();
  const memberId = useRef(props.match.params.id);
  const [detail, setDetail] = useState({} as any);
  const [formData, setFormData] = useState([] as FormListItem[]);
  const [occupationCode, setOccupationCode] = useState({});
  const [cardTypeOption, setCardTypeOption] = useState({});
  const [countryCode, setCountryCode] = useState({});
  const [provinceOptions, setProvinceOptions] = useState({});
  const [provinceId, setProvinceId] = useState<string>();
  const [cityOptions, setCityOptions] = useState({});
  const [cityId, setCityId] = useState<string>();
  const [areaOptions, setAreaOptions] = useState({});
  const [bankAreaOptions, setBankAreaOptions] = useState({});
  const [bankAreaId, setbankAreaId] = useState<string>();
  const [bankOptions, setBankOptions] = useState({});
  const formatData = (data: any) => {
    const result = [
      { label: '基本信息', valueKey: 'baseInfo', type: 'detailTitle' },
      { label: '证件类型', valueKey: 'cardTypeCode', type: 'text', content: cardTypeOption?.[data.cardTypeCode]?.label || data.cardTypeCode },
      { label: '证件号', valueKey: 'cardCode', type: 'text', content: data.cardCode },
      { label: '姓名(中文)', valueKey: 'chinaUserName', type: 'text', content: data.chinaUserName },
      { label: '性别', valueKey: 'sex', type: 'text', content: SEX_MAP[data.sex]?.label || data.sex },
      { label: '出生年月日', valueKey: 'birthday', type: 'text', content: data.birthday ? moment(data.birthday).format('YYYY-MM-DD') : undefined },
      { label: '出生地', valueKey: 'birthLocation', type: 'text', content: data.birthLocation },
      { label: '国籍/地区', valueKey: 'nationality', type: 'text', content: countryCode?.[data.nationality]?.label || data.nationality },
      { label: '是否居民', valueKey: 'resident', type: 'text', content: RESIDENT_TYPE_MAP?.[data.resident]?.label || data.resident },
      { label: '手机号', valueKey: 'mobile', type: 'text', content: data.mobile },
      { label: '职业代码', valueKey: 'occupationCode', type: 'text', content: occupationCode?.[data.occupationCode]?.label || data.occupationCode },
      { label: '工作单位', valueKey: 'workUnit', type: 'text', content: data.workUnit },
      { label: '人员状态', valueKey: 'peopleStatus', type: 'text', content: PEOPLE_STATUS_MAP?.[data.peopleStatus]?.label || data.peopleStatus },
      // { label: 'Email', valueKey: 'remarks', type: 'text', content: data.email },
      { label: '备注', valueKey: 'remarks', type: 'text', content: data.remarks },
      { label: '账户信息', valueKey: 'accountInfo', type: 'detailTitle' },
      { label: '开户姓名', valueKey: 'openAccountName', type: 'text', content: data.openAccountName },
      { label: '银行卡号', valueKey: 'bankAccount', type: 'text', content: data.bankAccount },
      { label: '开户行所属地区', valueKey: 'regionName', type: 'text', content: bankAreaOptions?.[data.regionName]?.label || data.regionName },
      { label: '开户行', valueKey: 'applyBank', type: 'text', content: bankOptions?.[data.applyBank]?.label || data.applyBank },
      // { label: '是否跨行', valueKey: 'isEnjambment', type: 'text', content: ENJAMBMENT_TYPE_MAP[data.isEnjambment]?.label },
      { label: '支付地', valueKey: 'payLocation', type: 'text', content: PAYLOCATION_TYPE_MAP?.[data.payLocation]?.label || data.payLocation },
      { label: '境外开户地(国别/地区)', valueKey: 'outsidePayLocation', type: 'text', content: data.outsidePayLocation },
      { label: '其他信息', valueKey: 'otherInfo', type: 'detailTitle' },
      { label: '是否雇员', valueKey: 'employee', type: 'text', content: ENJAMBMENT_TYPE_MAP?.[data.employee]?.label || data.employee },
      { label: '是否股东/投资者', valueKey: 'shareholder', type: 'text', content: ENJAMBMENT_TYPE_MAP?.[data.shareholder]?.label || data.shareholder },
      { label: '是否残疾烈属孤老', valueKey: 'special', type: 'text', content: ENJAMBMENT_TYPE_MAP?.[data.special]?.label || data.special },
      { label: '境内有无住所', valueKey: 'house', type: 'text', content: ISHAVE_MAP[data.house]?.label || data.house },
      { label: '首次入境时间', valueKey: 'firstToChinaTime', type: 'text', content: data.firstToChinaTime ? moment(data.firstToChinaTime).format('YYYY-MM-DD') : undefined },
      { label: '本年入境时间', valueKey: 'entryTime', type: 'text', content: data.entryTime ? moment(data.entryTime).format('YYYY-MM-DD') : undefined },
      { label: '来华时间', valueKey: 'toChinaTime', type: 'text', content: data.toChinaTime ? moment(data.toChinaTime).format('YYYY-MM-DD') : undefined },
      { label: '预计离境时间', valueKey: 'estimatedLeaveTime', type: 'text', content: data.estimatedLeaveTime ? moment(data.estimatedLeaveTime).format('YYYY-MM-DD') : undefined },
      { label: '居住省份', valueKey: 'residentialProvince', type: 'text', content: provinceOptions?.[data.residentialProvince]?.label || data.residentialProvince },
      { label: '居住城市', valueKey: 'residentialCity', type: 'text', content: cityOptions?.[data.residentialCity]?.label || data.residentialCity },
      { label: '居住所在区县', valueKey: 'residentialArea', type: 'text', content: areaOptions?.[data.residentialArea]?.label || data.residentialArea },
      { label: '居住详细地址', valueKey: 'residentialAddress', type: 'text', content: data.residentialAddress }
    ];
    setFormData(result);
  };

  const handleDelete = async () => {
    console.log('detail', detail);
    const params = {
      buttons: [
        {
          text: '删除',
          cb: async () => {
            const res = await DeleteOutsideUser(memberId.current);
            if (res.status === 200) {
              Toast.success('删除人员信息成功');
              props.history.replace('/member');
            }
          }
        }, {
          text: '取消'
        }
      ],
      message: `确认删除${detail?.openAccountName || ''}？`
    };
    SecondConfirm(params);
  };

  const handleEdit = () => {
    props.history.push(`/member/edit/${memberId.current}`);
  };

  const getButtonOptions = () => (
    [
      {
        text: '删除',
        icon: <i className="iconfont icon">&#xe6e0;</i>,
        onClick: handleDelete
      }, {
        text: '修改',
        icon: <i className="iconfont icon">&#xe6e1;</i>,
        onClick: handleEdit
      }
    ]
  );

  useEffect(() => {
    const getDetail = async () => {
      const res = await GetOutsideUserDetail(memberId.current);
      setDetail(res.data);
      setProvinceId(res.data?.residentialProvince);
      setCityId(res.data?.residentialCity);
      setbankAreaId(res.data?.regionName);
    };
    getDetail();
  }, []);


  useEffect(() => {
    detail && formatData(detail);
  }, [detail, occupationCode, cardTypeOption, countryCode, provinceOptions, cityOptions, areaOptions, bankAreaOptions, bankOptions]);

  /**
 * getOccupationCode 获取职业代码
 * getCardTypeCode 获取证件类型
 * getCountryCode 获取国家
 * getBankArea  获取开户行地区
*/

  useEffect(() => {
    const getOccupationCode = async () => {
      const data = await GetOccupationCode();
      const res = FormatDictData(data, 'value', 'label').map;
      setOccupationCode(res);
    };
    const getCountryCode = async () => {
      const data = await GetCountryCode();
      const res = FormatDictData(data, 'value', 'label').map;
      setCountryCode(res);
    };
    const getCardTypeCode = async () => {
      const data = await GetCardTypeCode();
      const res = FormatDictData(data, 'value', 'label').map;
      setCardTypeOption(res);
    };
    const getBankArea = async () => {
      const data = await GetBankArea();
      const res = FormatDictData(data, 'value', 'label').map;
      setBankAreaOptions(res);
    };
    getOccupationCode();
    getCountryCode();
    getCardTypeCode();
    getBankArea();
  }, []);
  //获取省
  useEffect(() => {
    const getProvince = async () => {
      const data = await GetProvince();
      const res = FormatDictData(data, 'value', 'label').map;
      setProvinceOptions(res);
    };
    getProvince();
  }, []);
  //获取市
  useEffect(() => {
    if (!provinceId) {
      setCityOptions([]);
      return;
    }
    const getCities = async () => {
      const data = await GetCities(provinceId);
      const res = FormatDictData(data, 'value', 'label').map;
      setCityOptions(res);
    };
    getCities();
  }, [provinceId]);
  //获取区
  useEffect(() => {
    if (!cityId) {
      setAreaOptions([]);
      return;
    }
    const getAreas = async () => {
      const data = await GetAreas(cityId);
      const res = FormatDictData(data, 'value', 'label').map;
      setAreaOptions(res);
    };
    getAreas();
  }, [cityId]);
  //获取开户行
  useEffect(() => {
    if (!bankAreaId) {
      setBankOptions([]);
      return;
    }
    const getBanks = async () => {
      const data = await GetBanks(bankAreaId);
      const res = FormatDictData(data, 'value', 'label').map;
      setBankOptions(res);
    };
    getBanks();
  }, [bankAreaId]);

  return (
    <div className={styles.wrap}>
      <div className={styles.title}>
        <div className={styles.avatar}>
          <Avatar name={detail?.openAccountName} />
        </div>
        <p className={styles.titleText}>{detail?.openAccountName}</p>
      </div>
      <FormGroup
        ref={formRef}
        formList={formData}
      />
      <ButtonFooterDetail
        data={getButtonOptions()}
      />
    </div>
  );
};

export default MemberDetail;